package beans;

import java.sql.*;
import javax.ejb.*;

public class CountriesBean extends AbstractBean {//implements EntityBean {

    private static final String COUNTRIES="countries";
    private static final String INSERTCOUNTRY="INSERT INTO countries (title) VALUES(?)";
    private static final String UPDATECOUNTRIES="UPDATE countries SET title=?";
    public String title;
    public int id;

    protected PreparedStatement queryForRemoveObj(Connection conn) throws SQLException {
        return conn.prepareStatement(DELETE+COUNTRIES+WHEREID);
    }

    protected PreparedStatement findBy(Connection conn, String byId) throws SQLException {
        return conn.prepareStatement(SELECTBYID+COUNTRIES+byId);
    }

    protected void loadEntity(PreparedStatement st, Connection conn) throws SQLException, NoSuchEntityException {
        st = conn.prepareStatement(SELECTENTITY+COUNTRIES+WHEREID);
        st.setInt(1, Integer.parseInt(context.getPrimaryKey().toString()));
        ResultSet rs = st.executeQuery();
        if (!rs.next()) {
            throw new NoSuchEntityException("Can't load next country");
        }
        title = rs.getString(2);
    }

    protected PreparedStatement storeEntity(Connection conn) throws SQLException {
        PreparedStatement st = conn.prepareStatement(UPDATECOUNTRIES+WHEREID);
        st.setString(1, title);
        st.setInt(2, Integer.parseInt(context.getPrimaryKey().toString()));
        return st;
    }

    public Integer ejbCreate(String title) throws CreateException {
        this.title = title;
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = ds.getConnection();
            st = conn.prepareStatement(INSERTCOUNTRY);
            st.setString(1, title);
            if (st.executeUpdate() != 1) {
                throw new CreateException("Can't create country, bad parametrs");
            }
            st = conn.prepareStatement(SELECTMAXID+COUNTRIES);
            ResultSet rs = st.executeQuery();
            /*if (!rs.next()) {
                throw new CreateException("...");
            }*/
            rs.next();
            int result = rs.getInt(1);
            return new Integer(result);
        } catch (SQLException ex) {
            throw new EJBException(ex);
        } finally {
            Util.closeConnection(conn, st);
        }
    }

    public void ejbPostCreate(String title) throws CreateException {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}
